namespace Ke.Paraleet.Hosts.Extensions;

/// <summary>
/// 启动后自动打开浏览器
/// </summary>
public static class LaunchBrowserExtensions
{
    /// <summary>
    /// 启动后自动打开浏览器
    /// </summary>
    /// <param name="app"></param>
    public static void LaunchBrowser(this WebApplication app)
    {
        // 方法B：使用IWebHostEnvironment获取URL信息
        var env = app.Services.GetRequiredService<IWebHostEnvironment>();

        var addressFeature = app.Services
            .GetRequiredService<Microsoft.AspNetCore.Hosting.Server.IServer>()
            .Features
            .Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()
            ;

        // 启动后自动打开浏览器
        app.Lifetime.ApplicationStarted.Register(() =>
        {
            // 优先使用实际监听的地址
            var actualUrl = addressFeature?.Addresses.FirstOrDefault();
            // 自动打开浏览器
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = actualUrl,
                    UseShellExecute = true
                });
            }
            catch
            {
                throw;
            }
        });
    }
}